/*
 * @Author: Kadu
 * @Date: 2021-06-26 13:08:18
 * @LastEditTime: 2021-06-26 23:46:34
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ttstar\assets\scripts\frameworks\UIRoot.ts
 */

import { Canvas, find, UITransform } from "cc";
import { GComponent } from "fairygui-cc";
import { UIMediator } from "./UIMediator";
import { UIWindow } from "./UIWindow";

export class UIRoot {

    private static windows: { [key: string]: UIWindow } = {};

    private static mainCanvas: Canvas;
    private static mainTransform: UITransform;

    /**
     * 主画布
     * @returns 
     */
    public static GetMainCanvas(): Canvas {
        if (!this.mainCanvas) {
            this.mainCanvas = find("Canvas")?.getComponent(Canvas) as any;
        }
        return this.mainCanvas;
    }

    /**
     * 主画布
     * @returns 
     */
    public static GetMainTransform(): UITransform {
        if (!this.mainTransform) {
            this.mainTransform = find("Canvas")?.getComponent(UITransform) as any;
        }
        return this.mainTransform;
    }

    /**
     * 关闭所有窗口
     * @param except 忽略除外
     */
    public static CloseOtherWindow(wind: UIWindow) {
        for (let key in this.windows) {
            let window = this.windows[key];
            if (window != wind && window.isBeClosed) {
                window.close();
            }
        }
    }

    public static GetWindow<T extends UIWindow>(c: { new(): T; }): T {
        let prototype = c as any;
        let objName = prototype["objName"];
        let wind = this.windows[objName] as T;
        if (!wind) {
            let resPath = prototype["resPath"];
            let resDeps = prototype["resDeps"];
            wind = new c();
            wind["resPath"] = resPath;
            wind["objName"] = objName;
            wind["resDeps"] = resDeps;
            this.windows[objName] = wind;
        }
        return wind;
    }

    public static GetWindowByName(name: string): UIWindow {
        return this.windows[name];
    }

    public static GetControl<T extends UIMediator>(view: GComponent): T {
        let behavior: T = (view as any)["behavior"];
        return behavior;
    }

    public static AttachControl<T extends UIMediator>(c: { new(): T; }, view: GComponent): T {
        let behavior: T = (view as any)["behavior"];
        if (!behavior) {
            behavior = new c();
            behavior.attach(view);
        }
        return behavior;
    }
}